<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right" style="font-size: 16px;">
      <el-breadcrumb-item :to="{ path: '/' }"><i class="el-icon-s-promotion"></i> 后台管理 </el-breadcrumb-item>
      <el-breadcrumb-item>员工管理 </el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 操作区域 -->
    <div style="margin: 0 0 20px 0;">
      <el-divider content-position="left">操作区域</el-divider>
      <el-button style="margin-left: 5px" type="primary" plain icon="el-icon-plus" @click="gotoAddNew()">添加用户</el-button>
      <el-button style="margin-right: 5px" type="warning" plain icon="el-icon-download" @click="exportExcelSelect">导出</el-button>
      <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="70px" style="float: right">
        <el-form-item label="用户名称" prop="username">
          <el-input v-model="queryParams.username" placeholder="请输入用户名称"
                    clearable style="width: 200px" @keyup.enter.native="search"></el-input>
        </el-form-item>
        <el-form-item label="电话号码" prop="phone">
          <el-input v-model="queryParams.phone" placeholder="请输入电话号码"
                    clearable style="width: 200px" @keyup.enter.native="search"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="search">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表格 -->
    <el-divider content-position="left">用户列表</el-divider>
    <el-table :data="tableData" border style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection"></el-table-column>
      <el-table-column type="index" width="50"></el-table-column>
      <el-table-column label="头像" width="150" align="center">
        <template slot-scope="scope">
          <el-avatar :size="30" :src="scope.row.avatar"></el-avatar>
        </template>
      </el-table-column>
      <el-table-column prop="username" label="用户名"  align="center"
                       :show-overflow-tooltip="true"></el-table-column>
      <el-table-column prop="phone" label="手机号码" align="center"
                       :show-overflow-tooltip="true"></el-table-column>
      <el-table-column prop="gmtCreate" label="创建日期"  align="center"
                       :show-overflow-tooltip="true"></el-table-column>
      <el-table-column prop="loginCount" label="登录次数"  align="center"
                       :show-overflow-tooltip="true"></el-table-column>
      <el-table-column label="是否启用" width="160" align="center">
        <template slot-scope="scope">
          <el-switch
              @change="toggleEnable(scope.row)"
              v-model="scope.row.enable"
              :active-value="1"
              :inactive-value="0"
              active-color="#13ce66"
              inactive-color="#999">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" align="center">
        <template slot-scope="scope">
          <el-button type="primary" icon="el-icon-edit" circle size="mini"
                     @click="openEditDialog(scope.row)"></el-button>
          <el-button type="danger" icon="el-icon-delete" circle size="mini"
                     @click="openDeleteConfirm(scope.row)"></el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 编辑用户信息表单 -->
    <el-dialog title="用户信息" :visible.sync="dialogFormVisible" :before-close="handleClose">
      <el-form :model="ruleForm" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="ruleForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="ruleForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="是否启用">
          <el-switch
              v-model="ruleForm.enable"
              :active-value="1"
              :inactive-value="0"
              active-color="#13ce66"
              inactive-color="#999">
          </el-switch>
        </el-form-item>
        <el-form-item label="角色" prop="roleIds">
          <el-select v-model="ruleForm.roleIds" multiple placeholder="请选择">
            <el-option
                v-for="item in roleListOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">确定</el-button>
          <el-button type="warning" @click="gotoList">返回列表</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 预览弹窗表格 -->
    <el-dialog title="表格保存预览" width="70%" :visible.sync="selectWindow">
      <el-table :data="selectData" id="selectTable" height="380px">
        <el-table-column type="index" width="50"></el-table-column>
        <el-table-column label="头像" width="150" align="center">
          <template slot-scope="scope">
            <el-avatar :size="30" :src="scope.row.avatar"></el-avatar>
          </template>
        </el-table-column>
        <el-table-column prop="username" label="用户名"  align="center"
                         :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="phone" label="手机号码" align="center"
                         :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="gmtCreate" label="创建日期"  align="center"
                         :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="loginCount" label="登录次数"  align="center"
                         :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="是否启用" width="160" align="center">
          <template slot-scope="scope">
            <el-switch
                @change="toggleEnable(scope.row)"
                v-model="scope.row.enable"
                :active-value="1"
                :inactive-value="0"
                active-color="#13ce66"
                inactive-color="#999">
            </el-switch>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footter">
        <el-button type="primary" @click="exportExcel">确定导出</el-button>
      </div>
    </el-dialog>

    <!-- 分页控件 -->
    <div style="padding: 10px 0">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrenChange"
          :current-page="pageNum"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>

  </div>
</template>

<script>
import BaseUrl from "@/http/BaseUrl";
import TokenAxios from "@/http/TokenAxios";
import FileSaver from "file-saver";
import XLSX from "xlsx";

export default {
  name:"UserManagementView.vue",
  data() {
    return {
      pageNum:1,
      pageSize:10,
      total:0,
      tableData:[],
      // 查询参数
      queryParams: {
        username: undefined,
        phone: undefined,
      },
      // 角色的下拉菜单的选项数据
      roleListOptions: [],
      // 表单
      ruleForm: {
        id: '',
        username: '',
        avatar: '',
        phone: '',
        enable: 1,
        roleIds: []
      },
      dialogFormVisible: false,
      // 导出
      selectData: [],
      selectWindow: false,
    }
  },
  methods:{
    handleClose(done) {
      this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {});
    },
    // 切换条数
    handleSizeChange(newSize){
      this.$router.replace('?size=' + newSize);
      this.loadUserList()
    },
    // 切换分页
    handleCurrenChange(newPage){
      this.$router.replace('?page=' + newPage);
      this.loadUserList()
    },
    // 加载用户列表
    loadUserList() {
      let page = this.$router.currentRoute.query.page;
      if (!page) {
        page = 1;
      }
      let size = this.$router.currentRoute.query.size;
      if (!size) {
        size = 10;
      }

      let url = BaseUrl.ADMIN_ACCOUNT + '/users?page=' + page + '&size=' + size;
      console.log('url = ' + url);

      TokenAxios.get(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.tableData = jsonResult.data.list;
          this.pageNum = jsonResult.data.pageNum;
          this.pageSize = jsonResult.data.pageSize;
          this.total = jsonResult.data.total;
        } else {
          let title = '操作失败';
          this.$alert(jsonResult.message, title, {
            confirmButtonText: '确定',
            callback: action => {}
          });
        }
      }).catch(error => {
        let title = '错误';
        let message = '程序执行过程中出现错误，请打开浏览器的控制台查看详细错误信息！';
        this.$alert(message, title, {
          confirmButtonText: '确定',
          callback: action => {
          }
        });
        console.log(error);
      });
    },
    // 处理删除功能
    handleDelete(user) {
      let url = BaseUrl.ADMIN_ACCOUNT + '/users/' + user.id + '/delete';
      console.log('url = ' + url);

      TokenAxios.post(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.$message({
            message: '删除【' + user.username + '】用户成功！',
            type: 'success'
          });
          this.loadUserList();
        } else if (jsonResult.state == 40400) {
          this.$alert(jsonResult.message, '操作失败', {
            confirmButtonText: '确定',
            callback: action => {
              this.loadUserList();
            }
          });
        } else {
          this.$alert(jsonResult.message, '操作失败', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      }).catch(error => {
        let title = '错误';
        let message = '程序执行过程中出现错误，请打开浏览器的控制台查看详细错误信息！';
        this.$alert(message, title, {
          confirmButtonText: '确定',
          callback: action => {
          }
        });
        console.log(error);
      });
    },
    // 点击删除提示
    openDeleteConfirm(user) {
      let message = '此操作将永久删除【' + user.username + '】用户，是否继续？';
      this.$confirm(message, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.handleDelete(user);
      }).catch(() => {
      });
    },
    // 切换启用状态
    toggleEnable(user) {
      let enableText = ['禁用', '启用'];
      let url = BaseUrl.ADMIN_ACCOUNT + '/users/' + user.id;
      let enable = user.enable;
      if (enable === 1) {
        url += '/enable';
      } else {
        url += '/disable';
      }
      console.log('url = ' + url);

      TokenAxios.post(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state === 20000) {
          this.$message({
            message: '将【' + user.username + '】的启用状态修改为【' + enableText[enable] + '】成功！',
            type: 'success'
          });
          this.loadUserList();
        } else if (jsonResult.state === 40400) {
          this.$alert(jsonResult.message, '操作失败', {
            confirmButtonText: '确定',
            callback: action => {
              this.loadUserList();
            }
          });
        } else {
          this.$alert(jsonResult.message, '操作失败', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
        this.loadUserList();
      }).catch(error => {
        let title = '错误';
        let message = '程序执行过程中出现错误，请打开浏览器的控制台查看详细错误信息！';
        this.$alert(message, title, {
          confirmButtonText: '确定',
          callback: action => {
          }
        });
        console.log(error);
      });
    },
    // 点击编辑功能
    openEditDialog(user){
      let url = BaseUrl.ADMIN_ACCOUNT + '/users/' + user.id;
      console.log('url = ' + url)
      this.id = user.id;
      TokenAxios.get(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state === 20000){
          this.ruleForm = jsonResult.data;
          this.dialogFormVisible = true;
        }else {
          let title = '操作失败';
          this.$alert(message, title,{
            confirmButtonText: '确定',
            callback:action => {}
          });
        }
      }).catch(error => {
        let title = '错误';
        let message = "执行程序过程中出现错误，请打开浏览器的控制台查看详细错误信息!";
        this.$alert(message,title,{
          confirmButtonText:'确定',
          callback:action => {}
        });
        console.log(error)
      })
    },
    // 确认表单
    submitForm() {
      let url = BaseUrl.ADMIN_ACCOUNT + '/users/' + this.ruleForm.id + '/update';
      console.log('url' + url);

      TokenAxios.post(url,this.ruleForm).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000){
          this.$message({
            message: '修改【' + this.ruleForm.username + '】用户成功！',
            type: 'success'
          });
          this.dialogFormVisible=false;
          this.loadUserList();
        }else if (jsonResult.state == 40400){
          this.$alert(jsonResult.message, '操作失败',{
            confirmButtonText: '确认',
            callback: action => {
              this.loadUserList();
            }
          });
        }else {
          this.$alert(jsonResult.message, '操作失败',{
            confirmButtonText: '确认',
            callback: action => {}
          });
        }
      }).catch(error => {
        let title = '错误';
        let message = '程序执行过程中出现错误，请打开浏览器的控制台查看详细错误信息！';
        this.$alert(message, title, {
          confirmButtonText: '确定',
          callback: action => {
          }
        });
        console.log(error);
      });
    },
    // 由编辑信息返回列表
    gotoList(){
      this.dialogFormVisible = false;
    },
    // 加载角色列表
    loadRoleList() {
      let url = BaseUrl.ADMIN_ACCOUNT + '/roles';
      console.log('url = ' + url);

      TokenAxios.get(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.roleListOptions = jsonResult.data.list;
        } else {
          let title = '操作失败';
          this.$alert(jsonResult.message, title, {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      }).catch(error => {
        let title = '错误';
        let message = '程序执行过程中出现错误，请打开浏览器的控制台查看详细错误信息！';
        this.$alert(message, title, {
          confirmButtonText: '确定',
          callback: action => {
          }
        });
        console.log(error);
      });
    },
    // 跳转到添加用户页面
    gotoAddNew(){
      this.$router.push('/admin/account/user/add-new')
    },
    // 点击搜索按钮
    search(){
      let url = BaseUrl.ADMIN_ACCOUNT + '/users/search';
      console.log('url = ' + url);
      TokenAxios.post(url,this.queryParams,this.pageNum,this.pageSize).then(response => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000){
          this.tableData = jsonResult.data.list;
        }else {
          let title = '操作失败';
          this.$alert(jsonResult.message, title, {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      }).catch(error => {
        let title = '错误';
        let message = '程序执行过程中出现错误，请打开浏览器的控制台查看详细错误信息！';
        this.$alert(message, title, {
          confirmButtonText: '确定',
          callback: action => {
          }
        });
        console.log(error);
      });
    },
    // 点击重置按钮
    resetQuery(){
      this.queryParams.username='';
      this.queryParams.phone='';
      this.loadUserList();
    },
    // 处理预览弹窗格式化数据
    getExcel(dom, title = '默认标题'){
      var excelTitle = title;
      var wb = XLSX.utils.table_to_book(document.querySelector(dom));
      // 获取二进制字符串作为输出
      var wbout = XLSX.write(wb,{bookType:"xlsx",bookSST:true,type:"array"});
      try {
        FileSaver.saveAs(
          new Blob([wbout],{type:"application/octet-stream"}),
          excelTitle + ".xlsx"
        );
      }catch (e){
        if (typeof console !== "undefined") console.log(e,wbout);
      }
      return wbout;
    },
    // 点击确定导出
    exportExcel(){
      this.getExcel('#selectTable', '用户登录的数据表格');
    },
    // 点击导出按钮显示预览弹窗
    exportExcelSelect(){
      if (this.selectData.length < 1){
        this.$message.error('请选择要导出的内容！');
        return false;
      }
      this.selectWindow=true
    },
    // 选中的数据
    handleSelectionChange(val){
      this.selectData = val;
    },
  },
  mounted() {
    this.loadUserList()
    this.loadRoleList()
  },
}
</script>

<style>
</style>
